package com.yksj.healthtalk.ui.buyandsell;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.BuyThingsAdapter;
import com.yksj.healthtalk.adapter.BuyThingsAdapter.onClickHeadSellerNumListener;
import com.yksj.healthtalk.adapter.BuyThingsAdapter.onClickHeaderListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.ImageGalleryActivity;
import com.yksj.healthtalk.entity.BuythingEntity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.DcotorServiceManagerEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.ui.recharge.ChoiseDateActivity;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonReadSelf;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 我买主页
 * @author Administrator
 *
 */
public class BuyOrSellInfoActivity extends BaseFragmentActivity implements OnClickListener,OnBuyTicketHandlerListener, OnRefreshListener<ListView>,onClickHeadSellerNumListener,onClickHeaderListener, OnItemClickListener, OnCheckedChangeListener{

	private TextView nowTime;//日历当前显示时间
	private String buyRecordSize;//购买的总条数
	private List<BuythingEntity> mBuyThingEntitys=new ArrayList<BuythingEntity>();
	private BuyThingsAdapter adapter;
	private String fileType;
	private String type="";//1 表示我买  2我卖
	private int pagNum=1;
	private TextView allMoney;
	private PullToRefreshListView refreshListView;
	RadioButton radioButton = null;
	private TextView buyRecord;
	private ListView mListView;
	private String date="";
	private PopupWindow mPopBottom;
	private View vPopView;
	private List<DcotorServiceManagerEntity> entitys;//右边标题分类
//	private String mServicetype="";
	private String SERVICETYPE;//

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.buy_main_ui);
		type = getIntent().getStringExtra("type");
		fileType=getIntent().getStringExtra("FILETYPE");
		initTitle();
		initView();
		initData();
	}

	
	private void initView() {
		String extra = getIntent().getStringExtra("titleName");
		titleTextV.setText(extra+"");
		titleLeftBtn.setOnClickListener(this);
		refreshListView = (PullToRefreshListView) findViewById(R.id.listview_fragment);
		mListView = refreshListView.getRefreshableView();
		findViewById(R.id.calender).setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		nowTime = (TextView)findViewById(R.id.now_time);
		nowTime.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
		nowTime.setOnClickListener(this);
		allMoney = (TextView)findViewById(R.id.all_money);
		buyRecord = (TextView)findViewById(R.id.buy_record);
		adapter=new BuyThingsAdapter(this,mBuyThingEntitys,type);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		adapter.setonClickHeaderListener(this);
		adapter.setonClickHeadSellerNumListener(this);
		refreshListView.setOnRefreshListener(this);
		pagNum=1;
		if(fileType.equals("5"))
		queryTitleOption();
		queryData(type,fileType,SERVICETYPE);
	}


	private void queryTitleOption() {
		titleRightBtn2.setText("服务类型");
		titleRightBtn2.setOnClickListener(this);
		HttpRestClient.doHttpDoctorSettingUI(new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				try {
					JSONArray array=new JSONArray(content);
					entitys = new ArrayList<DcotorServiceManagerEntity>();
					DcotorServiceManagerEntity allEntity = new DcotorServiceManagerEntity();
					allEntity.setOPEN_FLAG("0");
					allEntity.setSERVICE_TYPE("全部");
					allEntity.setSERVICE_TYPE_ID("");
					entitys.add(allEntity);
					for (int i = 0; i < array.length(); i++) {
						JSONObject object=(JSONObject) array.get(i);
						if(object.has("REMIND_ON_OFF")){
						}else{
							DcotorServiceManagerEntity entity=new DcotorServiceManagerEntity(); 
							entity.setOPEN_FLAG(object.optString("OPEN_FLAG"));
							entity.setSERVICE_TYPE(object.optString("SERVICE_TYPE"));
							entity.setSERVICE_TYPE_ID(object.optString("SERVICE_TYPE_ID"));
							entitys.add(entity);
							titleRightBtn2.setVisibility(View.VISIBLE);
						}
					}
				} catch (Exception e) {
				}
			}
		});
	}
	private void showMenu(View view) {
		if (mPopBottom == null) {
			LayoutInflater inflater = LayoutInflater.from(this);
			vPopView = inflater.inflate(R.layout.doctor_client_history, null);
			vPopView.setBackgroundResource(R.drawable.popmenu_white_bg);
			mPopBottom = new PopupWindow(vPopView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, true);
			mPopBottom.setBackgroundDrawable(new BitmapDrawable());
			mPopBottom.setFocusable(true);
			RadioGroup radioGroup = (RadioGroup) vPopView.findViewById(R.id.radiogroup);
			int size=entitys.size();
			for (int i = 0; i <size ; i++) {
				radioGroup.getChildAt(i).setVisibility(View.VISIBLE);
				RadioButton button=(RadioButton)radioGroup.getChildAt(i);
				button.setText(entitys.get(i).getSERVICE_TYPE());
			}
			radioGroup.setOnCheckedChangeListener(this);
		} else if (mPopBottom.isShowing()) {
			mPopBottom.dismiss();
			return;
		}
		mPopBottom.showAsDropDown(view);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data!=null){
		Bundle extras = data.getExtras();
		if(extras.containsKey("all")){
			date="";
			mBuyThingEntitys.clear();
			initData();
		}else{
			if(extras.containsKey("nothing"))return;
			String string = extras.getString("date");
			String string1 = extras.getString("year");
			nowTime.setText(string1+"-"+string);
			date=string1+string;
			pagNum=1;
			mBuyThingEntitys.clear();
			queryData(type,fileType,SERVICETYPE);
			}
		}else{
			date=null;
			nowTime.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
			queryData(type,fileType,SERVICETYPE);
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.calender:
		case R.id.now_time:
			Intent intent=new Intent(this,ChoiseDateActivity.class);
			if(nowTime.getText().toString().length()<5){
				intent.putExtra("date", TimeUtil.getMoneyTime());
			}else{
				intent.putExtra("date", nowTime.getText().toString());
			}
			startActivityForResult(intent,0);
			break;
		case R.id.title_right2:
			showMenu(v);
			break;
		}
	}
	

	/**
	 * 网络访问获取数据
	 * TYPE=2&CUSTOMERID=76&FILETYPE=1&TIME=201303&PAGENUM=1&PAGECOUNT=5
	 */
	public void queryData(final String type,String fileType,String SERVICETYPE) {
		HttpRestClient.doHttpBuyAndSellQueryData(type,SmartFoxClient.getLoginUserId(),fileType,date,pagNum+"","6",SERVICETYPE,new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				try {
					JSONObject object=new JSONObject(content);
					if(!"1".equals(pagNum+"")){
						mBuyThingEntitys.addAll(BuythingEntity.getParseToList(object.getString("DATA")));
					}else{
						mBuyThingEntitys.clear();
						mBuyThingEntitys.addAll(BuythingEntity.getParseToList(object.getString("DATA")));
					}
					
					buyRecordSize=object.getString("TOTALCOUNT");
					allMoney.setText(object.getString("TOTALCHARGING")+"元");
					if(type.equals("1")){
					buyRecord.setText("详细记录(共"+buyRecordSize+"条)");}else{
						buyRecord.setText("详细记录(共"+buyRecordSize+"条)");
					}
					
					adapter.notifyDataSetChanged();
					pagNum++;
					if(mBuyThingEntitys.size()==0){
						ToastUtil.showToastPanl("没有记录");
					}
				} catch (JSONException e) {
					refreshListView.onRefreshComplete();
				}
			}
			@Override
			public void onStart() {
				super.onStart();
				refreshListView.setRefreshing();
			}
			@Override
			public void onFinish() {
				super.onFinish();
				refreshListView.onRefreshComplete();
			}
		});
	}


	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			queryData(type,fileType,SERVICETYPE);
	}

	
	/**
	 * 查看大图
	 */
	@Override
	public void onClickHeaderClick(View v, BuythingEntity entity, int position) {
		if(fileType.equals("6")){//话题
			boolean contains = HTalkApplication.getAppData().getCreatedGroupIdList().contains(entity.getId());
			if(contains){
				Intent intent = new Intent();
				intent.setClass(BuyOrSellInfoActivity.this, SalonReadSelf.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			}else{
				Intent intent = new Intent();
				intent.setClass(BuyOrSellInfoActivity.this, SalonInformationActivity.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			}
		}else if(fileType.equals("5")){
		/*	Intent intent = new Intent();
			intent.setClass(BuyMainUI.this, FriendInformUI.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);*/
			CustomerInfoEntity listener = new CustomerInfoEntity();
			listener.setId(entity.getId());
			listener.setName(entity.getSellerName());
			FriendHttpUtil.onItemClick(this, listener);
		}else if(!mBuyThingEntitys.get(position).getAddressImage().equals("")){
			Intent intent = new Intent(this,ImageGalleryActivity.class);
			intent.putExtra(ImageGalleryActivity.URLS_KEY,new String[]{entity.getAddressImage()});
			intent.putExtra(ImageGalleryActivity.TYPE_KEY,0);//0,1单个,多个
			startActivity(intent);
		}
		
	}

		/**
		 * 显示购买者
		 */
	@Override
	public void onSalonHeadSellerNumClick(View v, BuythingEntity entity,
			int position) { String sellerNameId;
		if(fileType.equals("2")){
			sellerNameId=entity.getClientId();
		}else if(!fileType.equals("6")){
		sellerNameId = mBuyThingEntitys.get(position).getId();}
		else{
		sellerNameId = mBuyThingEntitys.get(position).getClientId();
		}
		Intent intent=new Intent(BuyOrSellInfoActivity.this,FriendInformUI.class);
		intent.putExtra("id", sellerNameId);
		startActivity(intent);
	}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {//fileType 6话题门票 5医生咨询  2照片 3语音 1文件 4视频
			Intent intent;
			HeaderViewListAdapter mAdapter=(HeaderViewListAdapter)parent.getAdapter();
			BuythingEntity mEntity= (BuythingEntity) mAdapter.getItem(position);
			switch (Integer.valueOf(fileType)) {
			case 1://文件 
				
				break;
			case 2://照片
					intent = new Intent(this,ImageGalleryActivity.class);
				   intent.putExtra(ImageGalleryActivity.URLS_KEY,new String[]{mEntity.getAddressImage()});
				   intent.putExtra(ImageGalleryActivity.TYPE_KEY,0);
				   intent.putExtra("type", 1);
				   startActivity(intent);
				break;
			case 3://语音
				
				break;
			case 4://视频
				
				break;
			case 5://医生咨询
				CustomerInfoEntity listener = new CustomerInfoEntity();
				listener.setId(mEntity.getId());
				listener.setName(mEntity.getSellerName());
				FriendHttpUtil.onItemClick(this, listener);
				break;
			case 6://话题门票 
				GroupInfoEntity entity = new GroupInfoEntity();
				entity.setId(mEntity.getId());
				SalonHttpUtil.onItemClick(getApplicationContext(), this, getSupportFragmentManager(), entity, true);
				break;
			}
		}


		@Override
		public void onTicketHandler(String state, GroupInfoEntity entity) {
			if ("0".equals(state)) {
				ToastUtil.showToastPanl("人民币不足");
			}else if("-1".equals(state)){
				ToastUtil.showShort(getApplicationContext(), "服务器出错");
			}else {
				Intent  intent1 = new Intent();
				intent1.putExtra(ChatActivity.KEY_PARAME,entity);
				intent1.setClass(this,ChatActivity.class);
				startActivity(intent1);
			}
		}



		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if(mPopBottom!=null&&mPopBottom.isShowing())mPopBottom.dismiss();
			RadioButton mButton= (RadioButton) vPopView.findViewById(group.getCheckedRadioButtonId());
			for (int i = 0; i < entitys.size(); i++) {
				if(mButton.getText().toString().equals(entitys.get(i).getSERVICE_TYPE())){
					SERVICETYPE=entitys.get(i).getSERVICE_TYPE_ID();
					date="";
					mBuyThingEntitys.clear();
					pagNum=1;
					nowTime.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
					queryData(type,fileType,SERVICETYPE);
				}
			}
		}
}
